using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Element
{
    public ELEMENT_STRUCT element_struct;
    public uint data
    {
        get
        {
            return this.element_struct.data;
        }
        set
        {
            this.element_struct.data = value;
        }
    }
    public int size
    {
        get
        {
            return this.element_struct.size;
        }
    }
    public Element_T type
    {
        get
        {
            return (Element_T)this.element_struct.type;
        }
    }
    public object val
    {
        get
        {
            switch (this.element_struct.type)
            {
                case 1: return (byte)this.data;
                case 2: return (UInt16)this.data;
                case 3: return (UInt32)this.data;
                case 4: return BitConverter.ToSingle(BitConverter.GetBytes(this.data));
                case 5: return BitConverter.ToInt16(BitConverter.GetBytes(this.data));
                case 6: return BitConverter.ToInt32(BitConverter.GetBytes(this.data));
                default: return (UInt32)this.data;
            }
            
        }
    }
    public Element(object val)
    {
        this.element_struct=dll_api.GetElement(val); 
    }
    public Element(ELEMENT_STRUCT element_struct)
    {
        this.element_struct = element_struct;
    }


}
public class Hluart : MonoBehaviour
{
    public static byte[] GetBuffer(Element[] elements)
    {
        int len = 0;
        foreach(Element e in elements)
        {
            len += e.size + 1;
        }
        byte[] temp = new byte[len];
        ELEMENT_STRUCT[] element_structs = new ELEMENT_STRUCT[elements.Length];
        for(int i = 0; i < elements.Length; i++)
        {
            element_structs[i] = elements[i].element_struct;
        }
        dll_api.write_buffer(temp, (uint)elements.Length, element_structs);

        return temp;
    }
    public static Element[] GetElements(byte[] buffer)
    {
        
        uint len = (uint)dll_api.get_elements_length(buffer, (short)buffer.Length);
        ELEMENT_STRUCT[] element_structs = new ELEMENT_STRUCT[len];
        dll_api.read_buffer(buffer, len, element_structs);

        List<Element> elements = new();
        for(int i = 0; i < len; i++)
        {

            elements.Add(new Element(element_structs[i]));
        }
        return elements.ToArray();
    }
}
